
package com.xgry.bpm.api.base.messageinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgry.bpm.api.base.messageinfo.entity.MessageInfo;
import com.xgry.bpm.api.base.messageinfo.service.MessageInfoService;
import com.xgry.bpm.api.base.messagesend.entity.MessageSend;
import com.xgry.bpm.api.base.messagesend.service.MessageSendService;
import com.xgry.bpm.api.base.messageuser.entity.MessageUser;
import com.xgry.bpm.api.base.messageuser.service.MessageUserService;
import com.xgry.bpm.api.base.userInfo.entity.UserInfo;
import com.xgry.bpm.api.base.userInfo.service.UserInfoService;
import com.xgry.bpm.common.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    *  前端控制器
    * </p>
 *
 * @author adrian
 * @since 2020-07-09
 * @version v1.0
 */
@RestController
@RequestMapping("/msg")
public class MessageInfoController {

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private MessageUserService messageUserService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private UserInfoService userInfoService;
    /*@Autowired
    private IDataService dataService;*/

    //保存并发送消息
    @RequestMapping(value = "createMsg.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional
    public Result createMsg(@RequestBody MessageInfo messageInfo) {

        String userId = messageInfo.getUserId();
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : userId.split(",")) {
            UserInfo userInfo = userInfoService.findByPersonnelId(Integer.parseInt(s));
            stringBuilder.append(userInfo.getUserId()).append(",");
        }
        messageInfo.setUserId(stringBuilder.toString().substring(stringBuilder.length()-1));
        messageInfoService.save(messageInfo);

        if ("MessageInfo".equals(messageInfo.getEntityName())) {
            for (String s : messageInfo.getUserId().split(",")) {
                MessageUser messageUser = new MessageUser();
                messageUser.setMsgInfoId(messageInfo.getMsgInfoId());
                messageUser.setUserId(Integer.parseInt(s));
                messageUser.setMsgUserId(null);
                messageUser.setStatus(0);
                messageUserService.save(messageUser);

                MessageSend messageSend = new MessageSend();
                messageSend.setIsDel(0);
                messageSend.setOldMsg(messageInfo.getOldMsg());
                messageSend.setMsgInfoId(messageInfo.getMsgInfoId());
                messageSend.setMsgText(messageInfo.getMsgText());
                messageSend.setMsgTitle(messageInfo.getMsgTitle());
                messageSend.setPushTime(messageInfo.getPushTime());
                messageSend.setStatus(0);
                messageSend.setUserId(Integer.parseInt(s));
                messageSend.setSendPeople(messageInfo.getSendPeople());
                messageSend.setSendName(messageInfo.getSendName());
                messageSendService.save(messageSend);
            }
        }

        return Result.success();
    }

    //打开收件箱消息(将status=0变为1) 请求参数为  MessageSend实体字段
    @RequestMapping(value = "openReciveMsg.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String openReciveMsg(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        MessageInfo messageInfo = JSONObject.parseObject(json.toJSONString(), MessageInfo.class);
        messageInfo.setUserId(userInfo.getUserId().toString());
        messageInfoService.updateById(messageInfo);

        if ("MessageSend".equals(messageInfo.getEntityName())) {
            MessageSend messageSend = JSONObject.parseObject(json.toJSONString(), MessageSend.class);
            List<MessageSend> list = messageSendService.list(new QueryWrapper<MessageSend>() {{
                this.eq("msg_send_id", messageSend.getMsgSendId());
                this.eq("is_del", 0);
            }});
            if (CollectionUtils.isEmpty(list)) {
                MessageSend messageSend1 = list.get(0);
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("msg_title",messageSend1.getMsgTitle());
                hashMap.put("msg_text",messageSend1.getMsgText());
                hashMap.put("old_message",messageSend1.getOldMsg());
                UserInfo userInfo1 = userInfoService.getById(Integer.parseInt(messageSend1.getSendPeople()));
                hashMap.put("send_peopleName",messageSend1.getSendPeople());
                hashMap.put("push_time",messageSend1.getPushTime());
                hashMap.put("status",1);

                result.put("status", HttpStatus.OK.value());
                result.put("statusName", HttpStatus.OK.name());
                result.put("data", hashMap);
            }
        }

        return result.toJSONString();
        /*try {
            json.put("user_id",userInfo.getUserId());

            dataService.Update(json);
            Object obj = dataService.FindById(json);
            if (obj != null) {
                SendMsgVo vo = new SendMsgVo();
                MessageSend msgSend = (MessageSend) obj;
                vo.setMsg_title(msgSend.getMsg_title());
                vo.setMsg_text(msgSend.getMsg_text());
                vo.setOld_msg(msgSend.getOld_msg());
                UserInfo send_people = userInfoService.findByUserInfoId(Integer.parseInt(msgSend.getSend_people()));
                vo.setSend_peopleName(send_people.getuName());
                vo.setPush_time(msgSend.getPush_time());
                vo.setStatus(1);
                json1.put("status", HttpStatus.OK.value());
                json1.put("statusName", HttpStatus.OK.name());
                json1.put("data", vo);
            } else {
                json1.put("status", HttpStatus.NO_CONTENT.value());//204  无数据返回
                json1.put("statusName", HttpStatus.NO_CONTENT.name());
                json1.put("message", "没有数据");
            }
            return json1.toJSONString();
        } catch (Exception e) {
            json1.put("status", HttpStatus.FAILED_DEPENDENCY.value());//720操作失败
            json1.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json1.put("message", "操作失败");
            return json1.toJSONString();
        }*/

    }


    //收件箱
    @RequestMapping(value = "msgInList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String msgInList(HttpSession session, @RequestBody String param) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(param);
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        List<Map<String,Object>> resultVo = new ArrayList<>();
        IPage<MessageSend> messageSendForPageAndSql = messageSendService.getMessageSendForPageAndSql(new Page<MessageSend>(
                        Integer.parseInt(jsonObject.getString("pageNum")),
                        Integer.parseInt(jsonObject.getString("pageSize"))),
                new MessageSend() {{
                    this.setUserId(userInfo.getUserId());
                    this.setIsDel(0);
                }},
                jsonObject.getString("paramSql"));
        for (MessageSend record : messageSendForPageAndSql.getRecords()) {
            for (String s : record.getSendPeople().split(",")) {
                UserInfo byId = userInfoService.getById(Integer.parseInt(s));
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("msg_send_id",record.getMsgSendId());
                hashMap.put("msg_title",record.getMsgTitle());
                hashMap.put("msg_text",record.getMsgText());
                hashMap.put("old_msg",record.getOldMsg());
                hashMap.put("send_people",record.getSendPeople());
                hashMap.put("send_peopleName",byId.getUName());
                hashMap.put("push_time",record.getPushTime());
                hashMap.put("status",record.getStatus());
                hashMap.put("userid",byId.getUserId());
                hashMap.put("userNames",userInfo.getUName());
                hashMap.put("msg_info_id",record.getMsgInfoId());
                resultVo.add(hashMap);
            }
        }
        result.put("count", messageSendForPageAndSql.getTotal());

        result.put("status", HttpStatus.OK.value());
        result.put("statusName", HttpStatus.OK.name());
        result.put("data", resultVo);
        return result.toJSONString();
    }

    //收件箱假删除单条消息(将is_del=0变为1)
    @RequestMapping(value = "updateIsDel.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional
    public String updateIsDel(@RequestBody JSONObject json, HttpSession session) {
        JSONObject json1 = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        try {
            if ("MessageSend".equals(json.getString("entityName"))) {
                MessageSend messageSend = JSONObject.parseObject(json.toJSONString(), MessageSend.class);
                messageSendService.updateById(messageSend);
            }
            if ("MessageInfo".equals(json.getString("entityName"))) {
                MessageInfo messageInfo = JSONObject.parseObject(json.toJSONString(), MessageInfo.class);
                messageInfoService.updateById(messageInfo);
            }

            json1.put("status", HttpStatus.OK.value());
            json1.put("statusName", HttpStatus.OK.name());
            json1.put("data", "该信息已删除");
            return json1.toString();
        } catch (Exception e) {
            json1.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json1.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json1.put("data", "异常");
            e.printStackTrace();
            return json1.toJSONString();
        }
    }


    //收件箱假删除多条
    @RequestMapping(value = "updateIsDels.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String updateIsDels(String[] ids, HttpSession session) {
        JSONObject json = new JSONObject();
        try {
            for (String msg_send_id : ids) {
                MessageSend messageSend = new MessageSend();
                messageSend.setMsgSendId(Integer.parseInt(msg_send_id));
                messageSend.setIsDel(1);
                messageSendService.updateById(messageSend);
            }
            return json.toJSONString();
        } catch (Exception e) {
            json.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json.put("data", "异常");
            e.printStackTrace();
            return json.toJSONString();
        }

    }

    //收件箱彻底删除
    @RequestMapping(value = "delReciveMsg.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String delReciveMsg(String[] ids, HttpSession session) {
        JSONObject json = new JSONObject();

        for (String msg_send_id : ids) {
            messageSendService.deleteById(msg_send_id);
        }
        json.put("status", HttpStatus.OK.value());
        json.put("statusName", HttpStatus.OK.name());
        json.put("data", "该信息已删除");
        return json.toJSONString();


    }

    //发件箱
    @RequestMapping(value = "msgOutList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String msgOutList(@RequestBody String param) {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(param);
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        List<Map<String,Object>> resultVo = new ArrayList<>();
        IPage<MessageInfo> messageInfoForPageAndSql = messageInfoService.getMessageInfoForPageAndSql(new Page<MessageInfo>(
                        Integer.parseInt(jsonObject.getString("pageNum")),
                        Integer.parseInt(jsonObject.getString("pageSize"))),
                new MessageInfo() {{
                    this.setUserId(jsonObject.getString("send_people"));
                    if ("1".equals(jsonObject.getString("ready_code"))) {
                        this.setIsDel("0");
                    } else {
                        this.setReadyCode("0");
                    }
                }},
                jsonObject.getString("paramSql"));

        for (MessageInfo messageInfo : messageInfoForPageAndSql.getRecords()) {
            List<UserInfo> userId = userInfoService.list(new QueryWrapper<UserInfo>() {{
                this.eq("userId", messageInfo.getUserId());
            }});
            String receivePeopleName = "";
            for (UserInfo info : userId) {
                receivePeopleName += info.getUName() + ",";
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("msg_info_id",messageInfo.getMsgInfoId());
            hashMap.put("msg_title",messageInfo.getMsgTitle());
            hashMap.put("msg_text",messageInfo.getMsgText());
            hashMap.put("old_msg",messageInfo.getOldMsg());
            hashMap.put("send_people",userInfo.getUserId());
            hashMap.put("send_peopleName",userInfo.getUName());
            hashMap.put("push_time",messageInfo.getPushTime());
            hashMap.put("status",messageInfo.getIsDel());
            hashMap.put("userid",messageInfo.getUserId());
            hashMap.put("ready_code","1");
            hashMap.put("userNames",receivePeopleName);
            resultVo.add(hashMap);
        }

        result.put("count", messageInfoForPageAndSql.getTotal());
        result.put("status", HttpStatus.OK.value());
        result.put("statusName", HttpStatus.OK.name());
        result.put("data", resultVo);
        return result.toJSONString();
    }

    //发件箱假删除单条信息(将is_del=0变为1)
    @RequestMapping(value = "updateSendIsDel.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String updateSendIsDel(@RequestBody JSONObject josn, HttpSession session) throws Exception {
        JSONObject json1 = new JSONObject();
        try {
            MessageInfo messageInfo = JSONObject.parseObject(josn.toJSONString(), MessageInfo.class);
            messageInfoService.updateById(messageInfo);
            json1.put("status", HttpStatus.OK.value());
            json1.put("statusName", HttpStatus.OK.name());
            json1.put("data", "该信息已删除");
            return json1.toJSONString();
        } catch (Exception e) {
            json1.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json1.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json1.put("data", "异常");
            e.printStackTrace();
            return json1.toJSONString();
        }

    }

    //发件箱假删除多条
    @RequestMapping(value = "updateSendIsDels.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String updateSendIsDels(String[] ids, HttpSession session) {
        JSONObject json = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        try {
            for (String msg_info_id : ids) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setIsDel("1");
                messageInfo.setMsgInfoId(Integer.parseInt(msg_info_id));
                messageInfoService.updateById(messageInfo);
            }
            json.put("status", HttpStatus.OK.value());
            json.put("statusName", HttpStatus.OK.name());
            json.put("data", "该信息已删除");
            return json.toJSONString();
        } catch (Exception e) {
            json.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json.put("data", "异常");
            e.printStackTrace();
            return json.toJSONString();
        }

    }

    //保存至草稿箱
    @RequestMapping(value = "readyMsg.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String readyMsg(@RequestBody JSONObject json, HttpSession session) throws Exception {
        JSONObject json1 = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        try {
            MessageInfo messageInfo = json.toJavaObject(MessageInfo.class);
            messageInfoService.save(messageInfo);
            json1.put("status", HttpStatus.OK.value());
            json1.put("statusName", HttpStatus.OK.name());
            json1.put("data", "保存草稿箱成功");
            return json1.toString();
        } catch (Exception e) {
            json1.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json1.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json1.put("data", "异常");
            e.printStackTrace();
            return json1.toJSONString();


        }
    }

    //草稿箱列表
    @RequestMapping(value = "readyMsgList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String readyMsgList(HttpSession session, @RequestBody String param) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(param);
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        List<Map<String,Object>> resultVo = new ArrayList<>();
        IPage<MessageInfo> messageInfoForPageAndSql = messageInfoService.getMessageInfoForPageAndSql(new Page<MessageInfo>(
                        Integer.parseInt(jsonObject.getString("pageNum")),
                        Integer.parseInt(jsonObject.getString("pageSize"))),
                new MessageInfo() {{
                    this.setUserId(jsonObject.getString("send_people"));
                    if ("1".equals(jsonObject.getString("ready_code"))) {
                        this.setIsDel("0");
                    } else {
                        this.setReadyCode("0");
                    }
                }},
                jsonObject.getString("paramSql"));

        for (MessageInfo messageInfo : messageInfoForPageAndSql.getRecords()) {
            String receivePeopleName = "";
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("msg_info_id",messageInfo.getMsgInfoId());
            hashMap.put("msg_title",messageInfo.getMsgTitle());
            hashMap.put("msg_text",messageInfo.getMsgText());
            hashMap.put("old_msg",messageInfo.getOldMsg());
            hashMap.put("send_people",userInfo.getUserId());
            hashMap.put("send_peopleName",userInfo.getUName());
            hashMap.put("push_time",messageInfo.getPushTime());
            hashMap.put("status",messageInfo.getIsDel());
            hashMap.put("userid",messageInfo.getUserId());
            hashMap.put("ready_code","0");

            for (String s : messageInfo.getUserId().split(",")) {
                UserInfo byId = userInfoService.getById(s);
                receivePeopleName += byId.getUName() + ",";
            }
            hashMap.put("userNames",receivePeopleName);
            resultVo.add(hashMap);
        }

        result.put("count", messageInfoForPageAndSql.getTotal());
        result.put("status", HttpStatus.OK.value());
        result.put("statusName", HttpStatus.OK.name());
        result.put("data", resultVo);
        return result.toJSONString();

    }


    //草稿箱删除多条(彻底删除)
    @RequestMapping(value = "delReadyMsgs.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional
    public String delReadyMsgs(String[] ids, HttpSession session) {
        JSONObject json = new JSONObject();

        try {
            for (String msg_info_id : ids) {
                messageInfoService.deleteById(msg_info_id);
            }
            json.put("status", HttpStatus.OK.value());
            json.put("statusName", HttpStatus.OK.name());
            json.put("data", "该信息已删除");
            return json.toJSONString();
        } catch (Exception e) {
            json.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            json.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
            json.put("data", "异常");
            e.printStackTrace();
            return json.toJSONString();
        }
    }


    /**
     * 收件箱未读消息条数
     */
    @RequestMapping(value = "CountMsg.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String CountMsg(HttpSession session) {
        JSONObject json = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        try {
            List<MessageSend> list = messageSendService.list(new QueryWrapper<MessageSend>() {{
                this.eq("is_del", "0");
                this.eq("status", "0");
                this.eq("user_id", userInfo.getUserId());
            }});
            json.put("CountMsg", list.size());
            return json.toString();
        } catch (Exception e) {
            json.put("countStatus", HttpStatus.FAILED_DEPENDENCY.value());
            json.put("countStatusName", HttpStatus.FAILED_DEPENDENCY.name());
            json.put("countData", "异常");
            e.printStackTrace();

        }
        return json.toJSONString();

    }


    /**
     * 收件箱未读消息
     * SELECT m.*,u.uName FROM message_send m left join user_info u on m.send_people = u.userId
     * where is_del = 0 and status = 0
     */
    @RequestMapping(value = "/findList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String findList() {
        JSONObject j = new JSONObject();
        try {
            int pageNum = 0;
            int pageSize = 20;
            IPage<MessageSend> messageSendListAndUserNameForPage = messageSendService.getMessageSendListAndUserNameForPage(
                    new Page<>(pageNum, pageSize),
                    new MessageSend(){{
                        this.setIsDel(0);
                        this.setStatus(0);
                    }});

            if (messageSendListAndUserNameForPage.getRecords().size() > 0) {
                j.put("data", messageSendListAndUserNameForPage.getRecords());
                j.put("countData", messageSendListAndUserNameForPage.getTotal());
                j.put("status", HttpStatus.OK.value());
                j.put("statusName", HttpStatus.OK.name());
            } else {
                j.put("data", "");
                j.put("status", HttpStatus.NOT_FOUND.value());
                j.put("statusName", HttpStatus.NOT_FOUND.name());
            }

        } catch (Exception e) {
            j.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            j.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
        }
        return j.toString();
    }


    /**
     * 收件箱未读消息
     */
    @RequestMapping(value = "/msgList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String msgList(@RequestBody String param) {
        JSONObject j = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(param);
        try {
            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            IPage<MessageSend> messageSendListAndUserNameForPage =
                    messageSendService.getMessageSendListAndUserNameForPage(
                            new Page<>(Integer.parseInt(jsonObject.getString("pageSize")),
                                    Integer.parseInt(jsonObject.getString("pageSize"))),
                            new MessageSend(){{
                                    this.setIsDel(0);
                                    this.setUserId(userInfo.getUserId());
                            }});

            if (messageSendListAndUserNameForPage.getRecords().size() > 0) {
                j.put("data", messageSendListAndUserNameForPage.getRecords());
                j.put("countData", messageSendListAndUserNameForPage.getTotal());
                j.put("status", HttpStatus.OK.value());
                j.put("statusName", HttpStatus.OK.name());
            } else {
                j.put("data", "");
                j.put("status", HttpStatus.NOT_FOUND.value());
                j.put("statusName", HttpStatus.NOT_FOUND.name());
            }

        } catch (Exception e) {
            j.put("status", HttpStatus.FAILED_DEPENDENCY.value());
            j.put("statusName", HttpStatus.FAILED_DEPENDENCY.name());
        }
        return j.toString();
    }
}
